<template>
  <div style="z-index:1100"> 
    <v-dialog
      fullscreen
      v-model="mySheet"
      :scrim="false"
    >
      <v-btn v-if="licenseStore.showBack" class="backBtn" icon="mdi-arrow-left"  @click="closed"></v-btn>

      <v-btn style="background:rgba(0, 0, 0, 0);"
        class="closeBtn"
        icon
        dark
        @click="close"
      >
        <v-icon style="opacity: 0;filter: progid:DXImageTransform.Microsoft.alpha(opacity=1);">mdi-close</v-icon>
      </v-btn> 
      <div style="z-index: 99999;position: absolute; bottom: 100px;color: #dedede;margin: 0 auto;text-align: center;width: 100%;" v-if="!networkStatus" v-show="networkShow&&myUrl.indexOf('offline')<=0">
        <span style="margin-right: 20px;" @click="networkShow=!networkShow">网络状态：离线</span>
        <v-btn @click="reloadURL"  class="flex-grow-1" style="margin-right: 20px;"
        height="48"
        variant="tonal">重新加载</v-btn>
        <v-btn @click="reloadWin"  class="flex-grow-1"
        height="48" color="#5865f2"
        variant="tonal">重启</v-btn>
       </div> 
      <v-card>
          <webview id="my-webview" nodeintegration="true" :src="myUrl" :preload="path+'/webview/webview-preload.js'" frameborder="0" width="100%" height="100%" style="width:100%;height:100%" v-if="path"/>
          <iframe  id="my-webview" style="vertical-align:bottom;width:100%;height:100%" frameborder="no" border="0" marginwidth="0" marginheight="0" scrolling="no"  :src="myUrl" width="100%" height="100%" v-else/>
          <!-- <webview :src="myUrl" preload="file:///Users/zhaohaiyuan/Downloads/work2023/edu-ai-app/edu-ai-ts-app/public/webview/webview-preload.js" frameborder="0" width="100%" height="100%" style="width:100%;height:100%"/> -->
      </v-card> 
    </v-dialog>  
  </div>
</template>
<script setup>
const networkStatus = ref(true)
const networkShow = ref(true)
let path=""; 
let projectTempPath="";
if(window.electronAPI){
  path=window.electronAPI.base();
  getProjectPath();
  window.electronAPI.getNetworkStatus((event, data)=>{ 
    if(!networkStatus.value&&data){
      proxy?.$Bus.emit('SystemInfoMsg', {msg:"网络已连接"});
      setTimeout(function(){
        proxy?.$Bus.emit('NetWorkReload', {});
        reloadWin();
      },1000) 
    }
    networkStatus.value=data;  
  })
}   
function getProjectOffline(){
   if(myUrl.value&&myUrl.value.indexOf("offline")>=0){
      return true;
   }else{
      return false;
   } 
}

async function getProjectPath(){
  // projectTempPath=await window.electronAPI.getTempFilePath();
  // projectTempPath=projectTempPath+"\\Project\\"; 
  projectTempPath="http://localhost:9999"
}
import { getCurrentInstance,ref, defineProps,computed,onMounted,nextTick} from 'vue'; 
import { useUserStore } from '../../stores/user'
import { useLicenseStore } from '../../stores/license'
import { useThemeStore } from '../../stores/theme'
const props = defineProps({
  sheet: Boolean,
  url:String
});  
const userStore = useUserStore() 
const licenseStore = useLicenseStore()  
const themeStore = useThemeStore()   
const {proxy} = getCurrentInstance();
const isLocked = ref(true)
const router = useRouter()
const emit = defineEmits(["update:sheet","update:url"]);
const mySheet = computed({
  get() {
    return props.sheet;
  },
  set(value) {
    emit("update:sheet", value);
  },
});
const countStep = ref(0);
const close = () => {
  if (countStep.value < 2) {
    countStep.value++;
  } else {
    mySheet.value=false;
    emit('update:sheet', false)
    // 可选：重置计数器
    countStep.value = 0;
  }  
}

const closed = () => { 
    mySheet.value=false;
    emit('update:sheet', false)
    // 可选：重置计数器
    countStep.value = 0; 
}
const myUrl = computed({
  get() { 
    return props.url;
  },
  set(value) {
    emit("update:url", value);
  },
});
onMounted(() => { 
  console.log('mounted!'); 
  if(!navigator.onLine){
    onPageEorr({})
    proxy?.$Bus.emit('SystemInfoMsg', {msg:"网络连接异常"});
  }
  reloadURL()  
}); 
onUnmounted(() => {
  proxy?.$Bus.off("ShowThemeWebURL",function(){});
});
//关闭
function handleClose(s){
  console.log(s)
  close();
}  
function updateQueryStringParameter(uri, key, value) {
    if(!value) { return uri }
    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
    }
    else {
        return uri + separator + key + "=" + value;
    }
}
proxy?.$Bus.off("ShowThemeWebURL",function(){});
proxy?.$Bus.on('ShowThemeWebURL', function(data){
  //未授权
  if(!((licenseStore.license||licenseStore.getAuth())||!licenseStore.license)){
    data.url=licenseStore.url
  }
  if(!data.url){
    return;
  }  
  let apiHost= "";
  if(userStore.apiHost){
    apiHost=userStore.apiHost;
  }   
  let myNewurl=updateQueryStringParameter(data.url,"agent",userStore.agent);
  if(data&&data.url&&data.url.indexOf("/")==0){ 
    myNewurl=apiHost+updateQueryStringParameter(data.url,"agent",userStore.agent);
  }
  if(myNewurl&&myNewurl==myUrl.value&&mySheet.value){
    return;
  }
  myUrl.value=myNewurl;  
  themeStore.setLastUrl(data.url);
  mySheet.value=true;  
  setTimeout(function(){
      bindWebView();
  },500); 
  //测试下网络情况
  setTimeout(function(){
    reloadNetworkData() 
  },3000);
})
// const webview=ref();
let myWebview;
var onlinefun=function(){
  console.log('有网络了');
  proxy?.$Bus.emit('SystemInfoMsg', {msg:"网络已连接"});
}
var offlinefun=function(){
  proxy?.$Bus.emit('SystemInfoMsg', {msg:"网络连接异常"});
}

var consolefun=function(e){
  console.log('log-webview: ' + e.message);
} 


var initEduDataFun=function(){
  try {
    let obj = {orgId:userStore.orgId,outputDeviceId:userStore.outputDeviceId}
    webview.executeJavaScript(`initEduData(${JSON.stringify(obj)})`)  
  } catch (error) {}  
}


var onPageEorr = function(e) {//处理webview发送过来的消息 
  // console.log('Load failed:', e.errorCode, e.errorDescription);
  networkStatus.value=false; 
  networkShow.value=true; 
} 
 
function bindWebView(){  
  const webview = document.querySelector('webview');
  // console.log('Now DOM is updated') 
  myWebview=webview;
  if(myWebview&&myUrl.value) {   
      try {
        webview.executeJavaScript(`window['outputDeviceId']='${userStore.outputDeviceId}'`) 
      } catch (error) {} 
      myWebview.addEventListener('dom-ready', initEduDataFun,false);
      myWebview.removeEventListener('console-message', consolefun,false); 
      myWebview.addEventListener('console-message', consolefun,false); 
      myWebview.addEventListener('ipc-message', onIpcMessage,false);//接收到webview过来的消息 
      myWebview.addEventListener('online',onlinefun,false);
      myWebview.addEventListener('offline',offlinefun,false);
      
      myWebview.addEventListener('did-fail-load', onPageEorr,false);
      myWebview.addEventListener('did-fail-provisional-load', onPageEorr,false);
  }
} 
function onIpcMessage(event) {//处理webview发送过来的消息
  const { channel, args } = event
  console.log(channel, args )
  if(channel=='showAiChat'){ 
    proxy?.$Bus.emit('ShowChatAI',{cmd:args})
  }else if(channel=='showAIPaper'){ 
    proxy?.$Bus.emit('ShowAIPaper',{cmd:args})
  }else if(channel=='showAIWordPaper'){ 
    proxy?.$Bus.emit('ShowAIWordPaper',{cmd:args})
  }else if(channel=='showWordPrint'){ 
    proxy?.$Bus.emit('ShowDataWordPrint',args[0])
  }
  // 处理完消息后再发送给webview
  myWebview.send(channel, 'success') //这里随便发个hahah给webview
}


function reloadNetworkData(){
   //在线的情况 
   if(!getProjectOffline()){
      window.electronAPI.checkNetwork({});  
   }
}

function reloadURL(){ 
  reloadNetworkData()
    //在线的情况
  if(!getProjectOffline()){
        
    if(networkStatus.value&&themeStore.lastUrl&&myUrl.value){
      setTimeout(function(){
        proxy?.$Bus.emit('ShowThemeWebURL',{url:themeStore.lastUrl});
      },2000); 
      setTimeout(function(){
        close()
      },1000);  
    }else{ 
      if(!networkStatus.value){
        proxy?.$Bus.emit('SystemInfoMsg', {msg:"请检查网络"});
      }  
    } 
  } 
 }

function reloadWin(){
  window.electronAPI.reloadWin({}); 
}
 
</script>
<style lang="scss"  scoped> 
.closeBtn{
  position: absolute;
  right: 20px;
  top: 20px;
  z-index: 1100;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0); /* 黑色阴影 */
} 
.backBtn{
  position: absolute;
  top: 0px;
  left: 20px;
  z-index: 1100;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0); /* 黑色阴影 */
  opacity: 0.3;
}
.dialog-bottom-transition-enter-active,
.dialog-bottom-transition-leave-active {
  transition: transform .2s ease-in-out;
}
</style>